﻿using Core.Identity.Common.Interfaces.Common.Interfaces;
using Core.Identity.Users.Dtos;
using Core.Interfaces.Users;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace Core.Identity.Users.Features.Queries.GetById;

#nullable disable

public class GetUserByIdQuery : IRequest<UserDetail>
{
    public Guid? UserId { get; set; }
}

public class GetUserByIdQueryHandler(
    IIdentityDbContext context,
    ICurrentUserService currentUserService) : IRequestHandler<GetUserByIdQuery, UserDetail>
{

    public async Task<UserDetail> Handle(GetUserByIdQuery request, CancellationToken cancellationToken)
    {
        var userId = request.UserId ?? currentUserService.GetUserId();

        var userDetail = await context.Users
            .AsNoTracking()
            .Where(u => u.Id == userId)
            .Select(u => new UserDetail
            {
                Id = u.Id,
                Username = u.Username,
                Nickname = u.Nickname,
                Email = u.Email,
                Avatar = u.Avatar,
                PhoneNumber = u.PhoneNumber,
                Lockout = u.Lockout,
                Roles = u.UserRoles
                    .Where(ur => ur.Role != null && ur.Role.Enabled == true)
                    .Select(ur => ur.Role!.Name)
                    .ToList(),
                Permissions = u.UserRoles
                    .Where(ur => ur.Role != null && ur.Role.Enabled == true)
                    .SelectMany(ur => ur.Role!.Permissions)
                    .Where(rp => rp.Permission.MenuType == 3)
                    .Select(rp => rp.Permission.Code)
                    .Distinct()
                    .ToList()
            })
            .FirstOrDefaultAsync(cancellationToken);

        if (currentUserService.IsSuperAdmin)
            userDetail.Permissions = await context.Permissions
                .AsNoTracking().Where(rp => rp.MenuType == 3)
                .Select(s => s.Code)
                .ToListAsync();

        return userDetail;
    }
}
